﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Health.Web;
using Microsoft.Health;
using Microsoft.Health.ItemTypes;
using EscaliWeightScale.ClinicalData;
using EscaliWeightScale.Security;

namespace EscaliWeightScale
{
    public partial class Form1 : Form
    {
        private ReadScale scale = null;
        private Timer Clock;
        public Form1()
        {
            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;
            this.FormBorderStyle = FormBorderStyle.None;
//            Start();
        }

        private void btnStartReading_Click(object sender, EventArgs e)
        {
            Start();
        }
        private void Start()
        {
            if (scale == null)
                scale = new ReadScale(lblWeight);

            Clock = new Timer();
            Clock.Interval = 1000;
            Clock.Start();
            Clock.Tick += new EventHandler(Timer_Tick);
        }
        private void Stop()
        {
            if (scale != null)
                scale.CloseScaleConnection();
            scale = null;
            Clock.Stop();
            lblStatusMessage.Text = "";
        }
        private void btnStopReading_Click(object sender, EventArgs e)
        {
            Stop();
        }
        public void Timer_Tick(object sender, EventArgs eArgs)
        {
            lblWeight.Refresh();
            Application.DoEvents();
            if (sender == Clock)
            {
                if (scale.lastTimeUpdated != DateTime.MinValue)
                {
                    if (!lblStatusMessage.Text.Equals("Discovered Weight."))
                    {
                        lblStatusMessage.ForeColor = Color.Gold;
                        lblStatusMessage.Text = "Listening for Weight Changes";
                        lblStatusMessage.Refresh();
                    }
                    if ((DateTime.Now - scale.lastTimeUpdated).TotalSeconds > 4)
                    {
                        if (!lblWeight.Text.Trim().Equals(string.Empty) && double.Parse(lblWeight.Text) > 0.0)
                        {
                            lblStatusMessage.ForeColor = Color.Green;
                            lblStatusMessage.Text = "Discovered Weight.";
                            lblStatusMessage.Refresh();
                            scale.lastTimeUpdated = DateTime.MinValue;
                            btnSendPF_Click(sender, eArgs);
                            lblWeight.Text = "";
                        }
                    }
                }
            }
        }
        private void btnSendHV_Click(object sender, EventArgs e)
        {
            try
            {
                //need to get the user logged in to HealthVault
                //List<PFSync.User> users = PFSync.User.RestoreAll();
                //PFSync.User u = users.First();

                PFSync.User u = new PFSync.User(4);

                //Guid appID = new Guid(System.Configuration.ConfigurationSettings.AppSettings["ApplicationId"]);
                //string healthServiceURL = System.Configuration.ConfigurationSettings.AppSettings["HealthServiceUrl"];
                //OfflineWebApplicationConnection connection = new OfflineWebApplicationConnection(appID, healthServiceURL, new Guid(u.PersonIdHV));
                // Authenticate connection
                //connection.Authenticate();

                //Pick the Weight off the label display.
                //Weight w = new Weight(new HealthServiceDateTime(DateTime.Now), new WeightValue(Math.Round(double.Parse(lblWeight.Text) * 0.45359237, 2), new DisplayValue(double.Parse(lblWeight.Text), "pounds", "lb")));

                //Send the Weight Data to HealthVault
                //HealthRecordAccessor accessor = new HealthRecordAccessor(connection, new Guid(u.RecordIdHV));
                //w.CommonData.Note = "Sent from Escali Scale";
                //accessor.NewItem(w);


                CLinicalData FusionData = new CLinicalData();
                FusionData.Url = "https://pfapi.com/PFAPI/ClinicalDataValue.asmx";

                Security.Security pfSecurity = new Security.Security();
                pfSecurity.Url = "https://pfapi.com/PFAPI/Security.asmx";
                LoginResult LoginResultClass = new LoginResult();
                EscaliWeightScale.Security.OperationStatus OperatingStatusObject = new EscaliWeightScale.Security.OperationStatus();

                LoginResultClass = pfSecurity.Login("petegordon", "5447693", out OperatingStatusObject);
                string pfVendorAPIToken = LoginResultClass.token.ToString();

                // Create a new ClinicalData object
                ClinicalData.ClinicalDataValue weight = new ClinicalDataValue();

                weight.ID = 82;
                weight.Source = "Sent from Escali Scale";
                weight.CollectedDateTime = DateTime.Now.ToUniversalTime();
                weight.Value = lblWeight.Text;

                EscaliWeightScale.ClinicalData.OperationStatus status = new EscaliWeightScale.ClinicalData.OperationStatus();
                FusionData.AddClinicalDataValue(pfVendorAPIToken, u.PatientIdPF, weight, weight.ID, out status);

                lblStatusMessage.ForeColor = Color.LightGreen;
                lblStatusMessage.Text = "Successfully sent " + lblWeight.Text + " to PatientFusion at "+DateTime.Now.ToString("h:mm tt");
            }
            catch (Exception ex)
            {
                lblStatusMessage.ForeColor = Color.Red;
                lblStatusMessage.Text = "Error trying to send to HealthVault";
                throw ex;
            }
        }

        private void btnSendPF_Click(object sender, EventArgs e)
        {
            try
            {
                //need to get the user logged in to HealthVault
                //List<PFSync.User> users = PFSync.User.RestoreAll();
                //PFSync.User u = users.First();

                PFSync.User u = new PFSync.User(4);

                //Guid appID = new Guid(System.Configuration.ConfigurationSettings.AppSettings["ApplicationId"]);
                //string healthServiceURL = System.Configuration.ConfigurationSettings.AppSettings["HealthServiceUrl"];
                //OfflineWebApplicationConnection connection = new OfflineWebApplicationConnection(appID, healthServiceURL, new Guid(u.PersonIdHV));
                //// Authenticate connection
                //connection.Authenticate();

                ////Pick the Weight off the label display.
                //Weight w = new Weight(new HealthServiceDateTime(DateTime.Now), new WeightValue(Math.Round(double.Parse(lblWeight.Text) * 0.45359237, 2), new DisplayValue(double.Parse(lblWeight.Text), "pounds", "lb")));

                ////Send the Weight Data to HealthVault
                //HealthRecordAccessor accessor = new HealthRecordAccessor(connection, new Guid(u.RecordIdHV));
                //w.CommonData.Note = "Sent from Escali Scale";
                //accessor.NewItem(w);

                CLinicalData FusionData = new CLinicalData();
                FusionData.Url = "https://pfapi.com/PFAPI/ClinicalDataValue.asmx";

                Security.Security pfSecurity = new Security.Security();
                pfSecurity.Url = "https://pfapi.com/PFAPI/Security.asmx";
                LoginResult LoginResultClass = new LoginResult();
                EscaliWeightScale.Security.OperationStatus OperatingStatusObject = new EscaliWeightScale.Security.OperationStatus();

                LoginResultClass = pfSecurity.Login("petegordon", "5447693", out OperatingStatusObject);
                string pfVendorAPIToken = LoginResultClass.token.ToString();

                // Create a new ClinicalData object
                ClinicalData.ClinicalDataValue weight = new ClinicalDataValue();

                weight.ID = 82;
                weight.Source = "Sent from Escali Scale";
                weight.CollectedDateTime = DateTime.Now.ToUniversalTime();
                weight.Value = lblWeight.Text;

                EscaliWeightScale.ClinicalData.OperationStatus status = new EscaliWeightScale.ClinicalData.OperationStatus();
                FusionData.AddClinicalDataValue(pfVendorAPIToken, u.PatientIdPF, weight, weight.ID, out status);

                lblStatusMessage.ForeColor = Color.LightGreen;
                lblStatusMessage.Text = "Successfully sent " + lblWeight.Text + " to PatientFusion at " + DateTime.Now.ToString("h:mm tt");
            }
            catch (Exception ex)
            {
                lblStatusMessage.ForeColor = Color.Red;
                lblStatusMessage.Text = "Error trying to send to HealthVault";
                throw ex;
            }
        }
    }
}
